package com.example.gybicycle.common.util;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {
    public static String zipfiles(List<String> paths,String filePath){
        if(paths==null||paths.size()==0)
            return null;
        String zipPath="/zip/"+"bycle_"+DataUtil.toString(new Date(),"yyMMddHHmm")+".zip";
        try {

            ZipOutputStream zipOut=new ZipOutputStream(new FileOutputStream(filePath+zipPath));
            for(String path:paths){
                fileToZip(path,zipOut);
            }
            zipOut.close();
            return zipPath;
        } catch (Exception e) {
            e.printStackTrace();
           return null;
        }

    }


    public static  void fileToZip(String filePath, ZipOutputStream zipOut){
        try{
           File file =new File(filePath);

           String fileName=file.getName();
            FileInputStream fileIn=new FileInputStream(filePath);
            byte[] bufferArea = new byte[1024 * 10];
            BufferedInputStream bufferStream = new BufferedInputStream(fileIn, 1024 * 10);
            zipOut.putNextEntry(new ZipEntry(fileName));
            int length=0;
            // 将当前文件作为一个zip实体写入压缩流,fileName代表压缩文件中的文件名称zipOut.putNextEntry(new ZipEntry(fileName));int length =0://最常规I0操作,不必紧张
            while((length = bufferStream.read(bufferArea,0,1024 *10))!= -1){
                zipOut.write(bufferArea,0,length);//关闭流fileInput.close();//需要注意的是缓冲流必须要关闭流,否则输出无效bufferstream.close(
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static List<String> upPaths(List<String> paths,String oldpath,String repath){
        List<String> rePaths=new ArrayList<>();
        for(String path:paths){
           String re= path.replace(oldpath,repath) ;
            rePaths.add(re);
        }
        return rePaths;
    }

    public static void main(String[] args) {
        List<String> paths= Arrays.asList("https://www.alexcycling.asia/image/rqcode/bike/BIKE202406170002.png","https://www.alexcycling.asia/image/rqcode/bike/BIKE202406170003.png","https://www.alexcycling.asia/image/rqcode/bike/BIKE202406170004.png","https://www.alexcycling.asia/image/rqcode/bike/BIKE202406170005.png","https://www.alexcycling.asia/image/rqcode/bike/BIKE202406170006.png");
        List<String>   rePath=upPaths(paths,"https://www.alexcycling.asia/image","D:\\image\\bike");
        zipfiles(rePath,"D:\\image\\bike");
    }
}
